package com.nsb.ihguapp.module;

import android.content.Context;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;

import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;

import java.util.List;

/**
 * wifi管理模块
 */
public class WifiManagerModule extends ReactContextBaseJavaModule {

    private WifiManager wifiManager = null;
    private List<ScanResult> list = null;

    public WifiManagerModule(ReactApplicationContext reactContext) {
        super(reactContext);
        wifiManager = (WifiManager) reactContext.getApplicationContext()
                .getSystemService(Context.WIFI_SERVICE);
    }

    /**
     * 此方法返回值作为rn调用时组件名称
     *
     * @return
     */
    @Override
    public String getName() {
        return "WifiManagerUtils";
    }

    /**
     * 获取wifi连接信息
     *
     * @return
     */
    private WifiInfo getWifiInfo() {
        if (null != wifiManager) {
            return wifiManager.getConnectionInfo();
        }

        return null;
    }

    /**
     * 获取周围wifi列表
     *
     * @param callback
     */
    @ReactMethod
    public void getAllWifiInfo(Callback callback) {
        StringBuffer wifiInfoStr = new StringBuffer();

        wifiManager.startScan();
        list = wifiManager.getScanResults();
        for (int x = 0; x < list.size(); x++) {
            wifiInfoStr.append(list.get(x).SSID + " : " + list.get(x).level + "dBm\n");
        }

        callback.invoke(wifiInfoStr.toString());
    }

    /**
     * 获取已连接wifi的信息
     *
     * @param callback
     */
    @ReactMethod
    public void getCurrentConnectWifiInfo(Callback callback) {
        WifiInfo wifiInfo = getWifiInfo();
        if (null == wifiInfo) {
            return;
        }

        String wifiInfoStr = new String();
        if (wifiInfo.getBSSID() != null) {
            //wifi名字 ,信号强度,连接速度
            wifiInfoStr = wifiInfo.getSSID() + " : " + wifiInfo.getRssi() + "dBm\n"
                    + "连接速度" + wifiInfo.getLinkSpeed() + "Mbps";
            callback.invoke(wifiInfoStr);
        }
    }
}
